
using System;
using System.Collections.Generic;

using Galaxium.Protocol.Xmpp.Library.Xml;

namespace Galaxium.Protocol.Xmpp.Library.Core
{
	public class QueryException: ApplicationException
	{
		public Stanza Stanza { get; private set; }
		
		public string ErrorType { get; private set; }
		public string Condition { get; private set; }
		public string Description { get; private set; }
		
		public QueryException (string type, string condition, string description)
		{
			ErrorType = type;
			Condition = condition;
			Description = description;
		}
		
		public QueryException (Stanza stanza)
		{
			if (stanza == null) {
				ErrorType = "cancel";
				Condition = "disconnected";
				Description = "You got disconnected while processing the request"; 
			}
			
			Stanza = stanza;
			var error = stanza.FirstChild ("error", null);
			try {
				ErrorType = error ["type"];
				Condition = error.FirstChild (null, Namespaces.Stanzas).Name;
			}
			catch { throw new ArgumentException (); }
			try { Description = stanza.FirstChild ("text", Namespaces.Stanzas).Text; }
			catch {}
		}
		
		public virtual Element ToXml ()
		{
			var elm = new Element (null, "error", null, "type", ErrorType.ToString ());
			elm.AppendChild (new Element (Condition, Namespaces.Stanzas));
			if (!String.IsNullOrEmpty (Description))
			    elm.AppendChild (new Element ("text", Namespaces.Stanzas).SetText (Description));
			return elm;
		}
	}
}